﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Telerik.Forums;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetForums()
		{
			List<MigrationForum> output = new List<MigrationForum>();

			IDictionary<string, ForumProvider> forumProviders = ForumManager.Providers;

			foreach (KeyValuePair<string, ForumProvider> forumProvider in forumProviders)
			{
				string providerName = forumProvider.Key;
				ForumManager forumManager = new ForumManager(providerName);

				IList forums = forumManager.GetForums(false);

				foreach (IForum forum in forums)
				{
					MigrationForum mf = new MigrationForum();
					if (forum.Category != null)
					{
						mf.CategoryDescription = forum.Category.Description;
						mf.CategoryName = forum.Category.Name;
					}
					else
					{
						mf.CategoryDescription = String.Empty;
						mf.CategoryName = String.Empty;
					}
					mf.DateCreated = forum.DateCreated;
					mf.DenyAnonymous = forum.DenyAnonymous;
					mf.Description = forum.Description;
					mf.Id = forum.ID;
					mf.ModeratePosts = forum.ModeratePosts;
					mf.Name = forum.Name;
					mf.ProviderName = providerName;
					mf.Status = forum.Status.ToString();

					foreach (IPost forumPost in forum.Posts)
					{
						MigrationForumPost mfp = new MigrationForumPost();
						mfp.AuthorIp = forumPost.AuthorIP;
						mfp.Content = forumPost.Content;
						mfp.DateCreated = forumPost.DateCreated;
						mfp.Id = forumPost.ID;
						mfp.Owner = forumPost.Owner;
						if (forumPost.Parent != null)
						{
							mfp.ParentId = forumPost.Parent.ID;
						}
						else
						{
							mfp.ParentId = Guid.Empty;
						}
						mfp.Status = forumPost.Status.ToString();
						if (forumPost.Thread != null)
						{
							mfp.ThreadId = forumPost.Thread.ID;
						}
						else
						{
							mfp.ThreadId = Guid.Empty;
						}
						mfp.Title = forumPost.Title;

						mf.Posts.Add(mfp);
					}

					output.Add(mf);
				}
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetForumsResponse", output);
		}
	}
}
